package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.SpinnerGridAdapter;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.QuestionE;
import com.infore.airsupervise.bean.StationGridE;
import com.infore.airsupervise.bean.UserE;
import com.infore.airsupervise.biz.QuestionDealBiz;
import com.infore.airsupervise.biz.UserAndGridBiz;
import com.infore.airsupervise.biz.impl.QuestionDealBizImpl;
import com.infore.airsupervise.biz.impl.UserAndGridBizImpl;
import com.infore.airsupervise.http.BaseResponse;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.SelectPhotoFragment;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.ImageUtil;
import com.infore.airsupervise.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 创建问题上报
 */
public class QuestionCreateActivity extends BaseTitleBarActivity implements AMapLocationListener {
    @BindView(R.id.et_create_title)
    EditText etCreateTitle;
    @BindView(R.id.et_create_code)
    EditText etCreateCode;
    @BindView(R.id.tv_handle_pson)
    TextView tvHandlePson;
    @BindView(R.id.sp_grid_area)
    Spinner spGridArea;
    @BindView(R.id.sp_grid_street)
    Spinner spGridStreet;
    @BindView(R.id.sp_grid_community)
    Spinner spGridCommunity;
    @BindView(R.id.et_create_detail)
    EditText etCreateDetail;
    @BindView(R.id.et_create_address)
    EditText etCreateAddress;
    @BindView(R.id.btn_location)
    AwesomeTextView btnLocation;

    private SpinnerGridAdapter areaAdapter;
    private SpinnerGridAdapter streetAdapter;
    private SpinnerGridAdapter communityAdapter;

    private List<StationGridE> streetList = new ArrayList<>();
    private List<StationGridE> communityList = new ArrayList<>();

    private SelectPhotoFragment selectPhotoFragment;
    private UserAndGridBiz gridBiz;
    private QuestionDealBiz questionDealBiz;

    private UserE userE;
    private StationGridE gridE; //网格信息
    private QuestionE questionE;
    private String gridId;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question_create);
        ButterKnife.bind(this);
        initTitleBar();
        setInfo();
        initPhotoSelect();
        setGridData();
        questionDealBiz = new QuestionDealBizImpl();

    }

    /**
     * titleBar 设置
     */
    private void initTitleBar() {
        title.setText("问题上报");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_CHECK);
    }

    /**
     * 上报人员信息
     */
    private void setInfo() {
        userE = UserE.getUserInfo();
        questionE = new QuestionE();
        tvHandlePson.setText(userE.getRealName());
        Date date = new Date();
        String mission_code = "Q" + userE.getAccount() + date.getTime();
        etCreateCode.setText(mission_code);
        intLocation();
    }

    /**
     * 初始化定位设置
     */
    private void intLocation() {
        locationClient = new AMapLocationClient(ctx);
        locationOption = new AMapLocationClientOption();
        locationClient.setLocationOption(locationOption);
        locationClient.setLocationListener(this);
    }

    /**
     * 适配器
     */
    private void setAdapter() {
        //区
        areaAdapter = new SpinnerGridAdapter(ctx, gridE.getBeanList());
        //街
        streetAdapter = new SpinnerGridAdapter(ctx, streetList);
        //社区
        communityAdapter = new SpinnerGridAdapter(ctx, communityList);
        spGridArea.setAdapter(areaAdapter);
        spGridStreet.setAdapter(streetAdapter);
        spGridCommunity.setAdapter(communityAdapter);
        //
        spGridArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                streetList.clear();
                if (i > 0) {
                    spGridStreet.setSelection(0);
                    streetList.addAll(gridE.getBeanList().get(i - 1).getBeanList());
                }
                streetAdapter.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        spGridStreet.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                communityList.clear();
                if (i > 0) {
                    spGridCommunity.setSelection(0);
                    communityList.addAll(streetList.get(i - 1).getBeanList());
                }
                communityAdapter.notifyDataSetChanged();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        spGridCommunity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if (i > 0) {
                    gridId = communityList.get(i - 1).getBh();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    /**
     * 设置网格信息
     */
    private void setGridData() {
        gridE = StationGridE.getGridList();
        if (null == gridE || null == gridE.getBeanList() || gridE.getBeanList().size() <= 0) {
            getGridData();
        } else {
            setAdapter();
        }
    }

    /**
     * 服务器获取网格信息
     */
    private void getGridData() {
        if (null == gridBiz) {
            gridBiz = new UserAndGridBizImpl();
        }
        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(ctx, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText("初始化网格信息");
        dialog.setCancelable(false);
        dialog.show();
        gridBiz.getGridInfoRequest("", new OnServerResponseListener<StationGridE>() {
            @Override
            public void onSucceed(StationGridE result, String desc) {
                dialog.dismiss();
                StationGridE.saveGridList(result);
                gridE = result;
                setAdapter();
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                dialog.dismiss();
                ToastUtil.showShort(ctx, "获取网格信息失败");
            }
        });
    }

    /**
     * 提交问题报告
     */
   private List<String> photoFiles = new ArrayList<>();
    private void commitQuesttionReport() {

        //loading dialog
        final SweetAlertDialog dialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING)
                .setContentText(MsgConst.PLEASE_WAITING);
        dialog.setCancelable(false);
        dialog.show();
        questionE.setQuestionNum(etCreateCode.getText().toString());//编号
        questionE.setQuestionTitle(etCreateTitle.getText().toString());//标题
        questionE.setQuestionContent(etCreateDetail.getText().toString());//内容
        questionE.setReleaseTime(DateUtil.getCurrentDateStr(true));//时间
        questionE.setGridNum(gridId);
        questionE.setQuestionAddress(etCreateAddress.getText().toString());
        //获取图片文件
        List<PhotoInfo> photoInfos = selectPhotoFragment.getSelectedPhotos();
        photoFiles.clear();
        photoFiles.addAll(ImageUtil.getInstance().compressOnUpload(photoInfos));
        questionDealBiz.sendQuestionCommitRequest(userE.getUserId(), questionE,photoFiles, new OnServerResponseListener<BaseResponse>() {
            @Override
            public void onSucceed(BaseResponse result, String desc) {
                //成功提示dialog
                dialog.setTitleText(MsgConst.OPERATION_SUCCESS)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                resultReturn();
                            }
                        })
                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
            }

            @Override
            public void onFailed(int errorCode, String title, String desc) {
                //失败提示dialog
                dialog.setTitleText(title)
                        .setContentText(desc)
                        .setConfirmText(MsgConst.I_SEE)
                        .changeAlertType(SweetAlertDialog.WARNING_TYPE);
            }
        });
    }

    @Override
    protected void onRightMenuClick(View view) {
        String str_alarm = "";
        if (etCreateTitle.getText().toString().isEmpty()) {
            str_alarm = "标题不能为空";
        } else if (etCreateDetail.getText().toString().isEmpty()) {
            str_alarm = "内容不能为空";
        } else if (TextUtils.isEmpty(gridId)) {
            str_alarm = "请选择网格";
        } else if (TextUtils.isEmpty(etCreateAddress.getText().toString())) {
            str_alarm = "地址不能为空";
        } else {
            commitQuesttionReport();
            return;
        }
        ToastUtil.showShort(ctx, str_alarm);
    }

    @OnClick(R.id.btn_location)
    public void onClick() {
        startLoction();
    }

    /**
     * 照片选择fragment
     */
    private void initPhotoSelect() {
        if (selectPhotoFragment == null) {
            selectPhotoFragment = new SelectPhotoFragment(5, 200);
        }
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().replace(R.id.rl_photo_select, selectPhotoFragment).commit();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        locationClient.stopLocation();
        btnLocation.setEnabled(true);
        btnLocation.clearAnimation();
        btnLocation.setFontAwesomeIcon(FontAwesome.FA_LOCATION_ARROW);
        if (null != aMapLocation) {
            if (aMapLocation.getErrorCode() == 0) { //定位成功
                etCreateAddress.setText(aMapLocation.getAddress());
            } else {
                String str_info[] = aMapLocation.getErrorInfo().split(" ");
                ToastUtil.showShort(ctx, str_info[0]);
            }
        }
    }

    private void startLoction() {
        locationClient.startLocation();
        btnLocation.setFontAwesomeIcon(FontAwesome.FA_CIRCLE_O_NOTCH);
        btnLocation.setAnimation(AnimationUtils.loadAnimation(ctx, R.anim.loading_animation));
        btnLocation.setEnabled(false);
    }

    /**
     * 销毁定位
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    private void resultReturn() {
        Intent it = new Intent();
        setResult(RESULT_OK, it);
        finish();
    }

}
